package com.aramis.mydytt.widget

import android.content.Context
import android.content.res.TypedArray
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import android.widget.RelativeLayout
import android.widget.TextView
import com.aramis.mydytt.R


/**
 * Description: SearchBar
 * @author lizhidan
 * Created: 2021/4/8
 */
class SearchBar : RelativeLayout {
    constructor(context: Context?) : super(context) {
        init(null)
    }

    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {
        init(attrs)
    }

    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        init(attrs)
    }

    var editMode = false
    var hintText = ""
    var editText: EditText? = null
    var onSearchClickListener: ((searchKey: String?) -> Unit)? = null

    private fun init(attrs: AttributeSet?) {
        LayoutInflater.from(context).inflate(R.layout.view_search_bar, this, true)
        initType(attrs)
        val hintTextView = findViewById<TextView>(R.id.search_bar_hint)
        hintTextView.text = hintText
        setBackgroundResource(R.drawable.bg_search_bar)
        if (editMode) {
            hintTextView.visibility = View.GONE
            editText = findViewById(R.id.edit_search_bar)
            editText?.visibility = View.VISIBLE
            editText?.hint = hintText
            editText?.requestFocus()

            editText?.setOnEditorActionListener { v, actionId, event ->
                var result = false
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    onSearchClickListener?.invoke(editText?.text?.toString())
                    result = true
                }
                result
            }
            findViewById<View>(R.id.search_bar_icon).setOnClickListener {
                onSearchClickListener?.invoke(editText?.text?.toString())
            }
        }
    }

    private fun initType(attrs: AttributeSet?) {
        val typedArray: TypedArray = context.obtainStyledAttributes(attrs, R.styleable.SearchBar)
        editMode = typedArray.getBoolean(R.styleable.SearchBar_editMode, editMode)
        hintText = typedArray.getString(R.styleable.SearchBar_hintText) ?: hintText
        typedArray.recycle()
    }
}